package com.dai.zhenfujin.addresslist;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RadioGroup;

import com.dai.zhenfujin.R;
import com.dai.zhenfujin.addresslist.fragment.AttentionViewPagerFragment;
import com.dai.zhenfujin.addresslist.fragment.FansViewPagerFragment;
import com.dai.zhenfujin.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * 通讯录
 */
public class AddressListFragment extends BaseFragment {
    private View view;
    private ViewPager viewPager;
    private RadioGroup radioGroup;
    private List<Fragment> fragments;

    @Override
    public View initView() {
        view = View.inflate(mContext, R.layout.fragment_addresslist,null);
        viewPager = view.findViewById(R.id.addresslist_pager);
        radioGroup = view.findViewById(R.id.addresslist_rg);
        radioGroup.check(R.id.addresslist_rb1);
        return view;
    }


    @Override
    public void initData() {
        super.initData();
        fragments = new ArrayList<>();
        fragments.add(new AttentionViewPagerFragment());
        fragments.add(new FansViewPagerFragment());
        //viewpaer一次加载全部页面
        viewPager.setOffscreenPageLimit(fragments.size());

        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        initListener();
    }

    private void initListener() {
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId){
                case R.id.addresslist_rb1:
                    viewPager.setCurrentItem(0);
                    break;
                case R.id.addresslist_rb2:
                    viewPager.setCurrentItem(1);
                    break;
            }
        });

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                //实现滑动页面下方按钮的联动
                radioGroup.check(radioGroup.getChildAt(i).getId());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    //适配器
    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }


        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }
}



